<template>
  <div class="dashboard">
    <!-- 顶部导航栏 -->
    <div class="nav-header">
      <div class="nav-tabs">
        <el-menu mode="horizontal" :default-active="activeNav" @select="handleNavSelect">
          <el-menu-item index="all">全部</el-menu-item>
          <el-menu-item index="recent">最近</el-menu-item>
          <el-menu-item index="video">视频</el-menu-item>
          <el-menu-item index="image">图片</el-menu-item>
          <el-menu-item index="doc">文档</el-menu-item>
          <el-menu-item index="trash">回收站</el-menu-item>
        </el-menu>
      </div>
      <div class="user-info">
        <span class="username">{{ username }}</span>
        <el-dropdown>
          <el-avatar :size="32" :src="userAvatar" />
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="handleLogout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
     <!-- 添加右键菜单组件 -->

      <!-- 主内容区 -->
      <div class="main-content">
        <!-- 操作栏 -->
        <div class="operation-bar">
          <div class="left-operations">
            <!-- 当有文件被选中时显示的操作菜单 -->
            <template v-if="selectedFiles.length > 0">
              <el-button-group>
                <template v-if="activeNav === 'trash'">
                  <el-button size="small" @click="handleBatchRestore">
                      <el-icon><RefreshLeft /></el-icon>恢复
                  </el-button>
                  <el-button size="small" type="danger" @click="handleBatchPermanentDelete">
                      <el-icon><Delete /></el-icon>彻底删除
                  </el-button>
                </template>
                <template v-else>
                  <el-button size="small" @click="handleBatchDownload">
                    <el-icon><Download /></el-icon>下载
                  </el-button>
                  <el-button size="small" @click="handleBatchShare">
                    <el-icon><Share /></el-icon>分享
                  </el-button>
                  <el-button size="small" @click="handleBatchCopy">
                    <el-icon><CopyDocument /></el-icon>复制到
                  </el-button>
                  <el-button size="small" @click="handleBatchMove">
                    <el-icon><Position /></el-icon>移动到
                  </el-button>
                  <el-button size="small" type="danger" @click="handleBatchDelete">
                    <el-icon><Delete /></el-icon>删除
                  </el-button>
                </template>
              </el-button-group>
            </template>
            <!-- 默认的操作按钮 -->
            
            <el-button type="primary" @click="showUploadDialog">
              <el-icon><Upload /></el-icon>上传文件
            </el-button>
            <el-button @click="showNewFolderDialog">
              <el-icon><FolderAdd /></el-icon>新建文件夹
            </el-button>
          </div>
          
          <div class="right-operations">
            <el-input
              v-model="searchQuery"
              placeholder="搜索文件"
              class="search-input"
              :prefix-icon="Search"
            />
            <el-radio-group v-model="viewMode" size="large">
              <el-radio-button label="list">
                <el-icon><List /></el-icon>
              </el-radio-button>
              <el-radio-button label="grid">
                <el-icon><Grid /></el-icon>
              </el-radio-button>
            </el-radio-group>
          </div>
        </div>
      <div class="path-navigation"  v-if="activeNav !== 'trash'">
        <el-button 
          v-if="currentPath !== '/'" 
          @click="handleBack"
          type="primary"
          plain
        >
          <el-icon><ArrowLeft /></el-icon>
          返回上级
        </el-button>
        <el-breadcrumb separator="/">
          <el-breadcrumb-item @click="navigateToRoot">根目录</el-breadcrumb-item>
          <el-breadcrumb-item 
            v-for="(path, index) in pathArray" 
            :key="index"
            @click="navigateTo(index)"
          >
            {{ path }}
          </el-breadcrumb-item>
        </el-breadcrumb>
      </div>

        <!-- 文件列表 -->
        <div class="file-list-container" :class="{ loading: loading }">
          <!-- 回收站为空时的显示 -->
          <div v-if="activeNav === 'trash' && (!filteredFiles || filteredFiles.length === 0)" class="empty-trash">
            <el-empty
              :image-size="200"
              description="您的回收站为空"
            >
              <template #description>
                <div class="empty-trash-text">
                  <p>回收站为空，删除的文件会在这里保存 10 天</p>
                  <p class="sub-text">开通超级会员 <el-link type="primary">延长至 30天</el-link></p>
                </div>
              </template>
            </el-empty>
          </div>

          <!-- 有文件时显示文件列表 -->
          <template v-else>
            <!-- 你原有的 el-table 部分保持不变 -->
            <el-table
              v-if="viewMode === 'list'"
              :data="filteredFiles"
              style="width: 100%"
              @selection-change="handleSelectionChange"
              @row-contextmenu="(row, column, event) => handleContextMenu(row, column, event)"
              v-loading="loading"
              @sort-change="handleSortChange"
            >
              <el-table-column type="selection" width="80" />
              <el-table-column label="文件名" min-width="400" sortable="custom" prop="name">
                <template #default="{ row }">
                  <div class="file-name" @dblclick="handleFileClick(row)">
                    <el-icon :size="40" :class="{ 'folder-icon': row.type === 'folder' }">
                      <component :is="getFileIcon(row.type)" />
                    </el-icon>
                    <span>{{ row.name }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="size" label="大小" width="120" sortable="custom">
                <template #default="{ row }">
                  {{ formatFileSize(row.size) }}
                </template>
              </el-table-column>
              <!-- 根据是否在回收站显示不同的列 -->
              <template v-if="activeNav === 'trash'">
                  <el-table-column prop="deletedAt" label="删除时间" width="180" sortable="custom" />
                  <el-table-column prop="retentionDays" label="有效时间" width="120" sortable="custom" >
                  <template #default="{ row }">
                      <el-tag :type="row.retentionDays < 7 ? 'danger' : 'info'">
                      {{ row.retentionDays }}天
                      </el-tag>
                  </template>
                  </el-table-column>
              </template>
              <template v-else>
                  <el-table-column prop="updateTime" label="修改时间" width="180" sortable="custom" />
              </template>
              <el-table-column label="操作" width="180" fixed="right">
                <template #default="{ row }">
                  <el-button-group>
                      <template v-if="activeNav === 'trash'">
                          <el-button size="small" @click="handleRestore(row)">
                              <el-icon><RefreshLeft /></el-icon>恢复
                          </el-button>
                          <el-button size="small" type="danger" @click="handlePermanentDelete(row)">
                              <el-icon><Delete /></el-icon>彻底删除
                          </el-button>
                      </template>
                      <template v-else>
                          <el-button size="small" @click="handleDownload(row)" :icon="Download" />
                          <el-button size="small" @click="handleShare(row)" :icon="Share" />
                          <el-button size="small" type="danger" @click="handleDelete(row)" :icon="Delete" />
                      </template>
                  </el-button-group>
                </template>
              </el-table-column>
            </el-table>

            <!-- 你原有的网格视图保持不变 -->
            <div v-else class="grid-view">
              <div
                v-for="file in filteredFiles"
                :key="file.id"
                class="grid-item"
                @dblclick="handleFileClick(file)"
                @contextmenu="(event) => handleContextMenu(file, null, event)"
              >
                <el-icon :size="40" :class="{ 'folder-icon': file.type === 'folder' }">
                  <component :is="getFileIcon(file.type)" />
                </el-icon>
                <div class="file-name">{{ file.name }}</div>
              </div>
            </div>
                <!-- 添加分页组件 -->
            <div class="pagination-container" v-if="activeNav === 'trash'">
            <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="total"
                layout="total, sizes, prev, pager, next"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </template>
        </div>
      </div>

      <!-- 各种对话框组件 -->
      <upload-dialog v-model="uploadDialogVisible" :current-path="currentPath" :files="files" @upload-success="handleUploadSuccess" />
      <new-folder-dialog v-model="newFolderDialogVisible" :current-path="currentPath" @create-success="handleFolderCreated" />
      <share-dialog v-model="shareDialogVisible" :file="selectedFile" @share-success="handleShareSuccess" />
      <preview-dialog v-model="previewDialogVisible" :file="selectedFile" />

  </div>
</template>

<style scoped>

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.file-list-container {
  transition: opacity 0.3s ease;
}

.loading {
  opacity: 0.6;
}




/* 右键菜单样式 */
.v-contextmenu {
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  padding: 8px 0;
}

.v-contextmenu-item {
  padding: 8px 16px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
}

.v-contextmenu-item:hover {
  background: #f5f7fa;
}

.v-contextmenu-divider {
  margin: 4px 0;
  border-top: 1px solid #ebeef5;
}

/* 文件夹图标样式 */
:deep(.folder-icon) {
  color: #ff9900 !important;  /* 使用 !important 确保样式生效 */
}

/* 调整图标大小 */
.file-name .el-icon {
  font-size: 24px;
}

.grid-item .el-icon {
  font-size: 48px;
}

.dashboard {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f6f6f6;
}


.nav-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  height: 60px;
  background-color: #fff;
  border-bottom: 1px solid #e6e6e6;
}

.nav-tabs {
  flex: 1;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.username {
  font-size: 14px;
  color: #606266;
}

.main-content {
  flex: 1;
  padding: 20px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background: white;
  padding: 16px;
  border-radius: 8px;
  position: sticky;
  top: 0;
  z-index: 1;
  background: white;
}

.el-button-group {
  margin-right: 16px;
}

.left-operations {
  display: flex;
  gap: 12px;
}

.right-operations {
  display: flex;
  align-items: center;
  gap: 16px;
}

.search-input {
  width: 300px;
}

.file-list-container {
  flex: 1;
  background: white;
  border-radius: 8px;
  padding: 16px;
  overflow: auto;
}

.file-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.grid-view {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 20px;
  padding: 20px;
}

.grid-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 10px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.grid-item:hover {
  background-color: #f5f7fa;
}

.grid-item .file-name {
  width: 100%;
  text-align: center;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

:deep(.el-menu--horizontal) {
  border-bottom: none;
}

:deep(.el-table) {
  border-radius: 8px;
}

.empty-trash {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400px;
  padding: 40px;
}

.empty-trash-text {
  text-align: center;
  color: #909399;
}

.empty-trash-text p {
  margin: 8px 0;
}

.empty-trash-text .sub-text {
  font-size: 14px;
  color: #909399;
}

.empty-trash :deep(.el-link) {
  font-weight: bold;
  text-decoration: none;
}

.empty-trash :deep(.el-empty__description) {
  margin-top: 20px;
}

</style>



<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Delete, Download, Share, Upload, FolderAdd,
  Document, Folder, Picture, VideoCamera, Grid, List, Edit,ArrowLeft, CopyDocument, Position 
} from '@element-plus/icons-vue'
import UploadDialog from '../components/UploadDialog.vue'  
import NewFolderDialog from '../components/NewFolderDialog.vue'
import ShareDialog from '../components/ShareDialog.vue'
import PreviewDialog from '../components/PreviewDialog.vue'
import { getFileList, deleteFile, renameFile,getTrashList,downloadFile,restoreFile,permanentlyDeleteFile } from '@/api/file'
import ContextMenu from '@imengyu/vue3-context-menu'
import { RefreshLeft } from '@element-plus/icons-vue'


const userAvatar = ref('path/to/avatar')  // 定义 userAvatar


// 添加排序相关的变量
const sortBy = ref('')
const sortOrder = ref('')

// 处理排序变化
const handleSortChange = ({ prop, order }) => {
  console.log('Sorting:', prop, order) // 添加调试日志
  
  if (!prop || !order) return
  
  const sortedFiles = [...files.value].sort((a, b) => {
    let comparison = 0
    
    switch (prop) {
      case 'name':
        // 文件夹优先排序
        if (a.isFolder !== b.isFolder) {
          return a.isFolder ? -1 : 1
        }
        return a.name.localeCompare(b.name)
        
      case 'size':
        // 文件夹大小为 0
        const sizeA = a.isFolder ? 0 : Number(a.size)
        const sizeB = b.isFolder ? 0 : Number(b.size)
        return sizeA - sizeB
        
      case 'updateTime':
        const timeA = new Date(a.updateTime || 0).getTime()
        const timeB = new Date(b.updateTime || 0).getTime()
        return timeA - timeB
        
      case 'deletedAt':
        const deleteTimeA = new Date(a.deletedAt || 0).getTime()
        const deleteTimeB = new Date(b.deletedAt || 0).getTime()
        return deleteTimeA - deleteTimeB
        
      case 'retentionDays':
        return (a.retentionDays || 0) - (b.retentionDays || 0)
        
      default:
        return 0
    }
  })

  // 根据排序方向调整结果
  files.value = order === 'ascending' ? sortedFiles : sortedFiles.reverse()
}

const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 在其他方法定义附近添加
const handleCurrentChange = (page) => {
  currentPage.value = page
  loadTrashList()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadTrashList()
}


// 添加批量操作方法
const handleBatchDownload = () => {
  // 实现批量下载
  console.log('批量下载:', selectedFiles.value)
}

const isTrash = computed(() => store.state.fileList.isTrash)

const handleBatchRestore = async () => {
    try {
        await ElMessageBox.confirm(
            `确定要恢复选中的 ${selectedFiles.value.length} 个文件吗？`,
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'info'
            }
        )
        // TODO: 调用批量恢复 API
        ElMessage.success('恢复成功')
        loadTrashList()
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('恢复失败')
        }
    }
}

const handleBatchPermanentDelete = async () => {
    try {
        await ElMessageBox.confirm(
            `确定要彻底删除选中的 ${selectedFiles.value.length} 个文件吗？此操作不可恢复！`,
            '警告',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        // 记录成功和失败的文件
        const results = {
            success: [],
            failed: []
        }

        // 并行处理所有删除请求
        const deletePromises = selectedFiles.value.map(async (file) => {
            try {
                await permanentlyDeleteFile(file.id,file.name)
                results.success.push(file.name)
            } catch (error) {
                results.failed.push({
                    name: file.name,
                    error: error.response?.data?.msg || error.message
                })
            }
        })

        // 等待所有删除操作完成
        await Promise.all(deletePromises)

        // 显示结果消息
        if (results.success.length > 0) {
            ElMessage.success(`成功删除 ${results.success.length} 个文件`)
        }
        
        if (results.failed.length > 0) {
            ElMessage.error(`${results.failed.length} 个文件删除失败：\n${
                results.failed.map(f => `${f.name}: ${f.error}`).join('\n')
            }`)
        }

        // 刷新列表
        loadTrashList()
        
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('操作取消')
        }
    }
}


const handleBatchShare = () => {
  // 实现批量分享
  console.log('批量分享:', selectedFiles.value)
}

const handleBatchCopy = () => {
  // 实现批量复制
  console.log('批量复制:', selectedFiles.value)
}

const handleBatchMove = () => {
  // 实现批量移动
  console.log('批量移动:', selectedFiles.value)
}

const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedFiles.value.length} 个文件吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 实现批量删除
    for (const file of selectedFiles.value) {
      await deleteFile(file.id,file.name)
    }
    
    ElMessage.success('删除成功')
    loadFileList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 修改处理函数
const handleContextMenu = (row, column, event) => {
  event.preventDefault()
  
  ContextMenu.showContextMenu({
    x: event.clientX,
    y: event.clientY,
    items: [
      {
        label: '打开',
        
        onClick: () => handleFileClick(row)
      },
      {
        label: '下载',
       
        onClick: () => handleDownload(row)
      },
      {
        label: '分享',
        
        onClick: () => handleShare(row)
      },
      {
        type: 'separator'
      },
      {
        label: '重命名',
        
        onClick: () => handleRename(row)
      },
      {
        label: '删除',
        
        onClick: () => handleDelete(row),
        
      }
    ]
  })
}



// 重命名处理函数
const handleRename = async (file) => {
  try {
    const { value: newName } = await ElMessageBox.prompt('请输入新名称', '重命名', {
      inputValue: file.name,
      inputValidator: (value) => value.trim() !== '',
      inputErrorMessage: '名称不能为空'
    })
    
    if (newName) {
      // TODO: 调用重命名 API
      await renameFile({
        fileId: file.id,
        newName: newName.trim()
      })  
      ElMessage.success('重命名成功')
      loadFileList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.msg)
    }
  }
}

// 计算当前路径数组
const pathArray = computed(() => {
  return currentPath.value.split('/').filter(Boolean)
})

// 返回上级目录
const handleBack = () => {
  const paths = currentPath.value.split('/').filter(Boolean)
  paths.pop()
  currentPath.value = '/' + paths.join('/') + (paths.length > 0 ? '/' : '')
  loadFileList()
}

// 导航到根目录
const navigateToRoot = () => {
  currentPath.value = '/'
  loadFileList()
}

// 导航到指定层级
const navigateTo = (index) => {
  const paths = pathArray.value.slice(0, index + 1)
  currentPath.value = '/' + paths.join('/') + '/'
  loadFileList()
}

const router = useRouter()
const username = ref(localStorage.getItem('username') || '未登录')
const activeNav = ref('all')
const viewMode = ref('list')
const searchQuery = ref('')
const loading = ref(false)
const currentPath = ref('/')
const files = ref([])
const selectedFiles = ref([])
const selectedFile = ref(null)

// 对话框控制
const uploadDialogVisible = ref(false)
const newFolderDialogVisible = ref(false)
const shareDialogVisible = ref(false)
const previewDialogVisible = ref(false)

// 计算过滤后的文件列表
const filteredFiles = computed(() => {
  let result = files.value
  
  // 搜索过滤
  if (searchQuery.value) {
    result = result.filter(file => 
      file.name.toLowerCase().includes(searchQuery.value.toLowerCase())
    )
  }
  
  return result
})

// 获取文件图标
const getFileIcon = (type) => {
  switch (type) {
    case 'folder': return Folder
    case 'image': return Picture
    case 'video': return VideoCamera
    default: return Document
  }
}

// 格式化文件大小
const formatFileSize = (size) => {
  if (size === 0) return '-'
  if (size < 1024) return size + 'B'
  if (size < 1024 * 1024) return (size / 1024).toFixed(2) + 'KB'
  if (size < 1024 * 1024 * 1024) return (size / 1024 / 1024).toFixed(2) + 'MB'
  return (size / 1024 / 1024 / 1024).toFixed(2) + 'GB'
}

// 处理导航选择
const handleNavSelect = (index) => {
  activeNav.value = index
  if (index === 'trash') {
    loadTrashList()
  } else {
    loadFileList(index)  // 传入文件类型
  }
}


// 加载普通文件列表
const loadFileList = async (type = 'all') => {
  loading.value = true
  try {


    const res = await getFileList({ 
      type: type,  // 文件类型：all, video, image, doc 等
      path: currentPath.value 
    })

    if (res.data.code === 200) {
      files.value = res.data.data.files

    } else {
      ElMessage.error(res.data.msg || '获取文件列表失败')
    }
  } catch (error) {
    console.error('Load file list error:', error)
    ElMessage.error('获取文件列表失败')
  } finally {
    loading.value = false
  }
}

// 单独处理回收站列表
const loadTrashList = async () => {
  loading.value = true
  try {

    const res = await getTrashList({
        page: currentPage.value,
        pageSize: pageSize.value
    })
    if (res.data.code === 200) {
      files.value = res.data.data.files
      total.value = res.data.data.total

    } else {
      ElMessage.error(res.data.msg || '获取回收站列表失败')
    }
  } catch (error) {
    console.error('Load trash list error:', error)
    ElMessage.error('获取回收站列表失败')
  } finally {
    loading.value = false
  }
}

// 处理恢复文件
const handleRestore = async (file) => {
  try {
    await ElMessageBox.confirm(
      `确定要恢复 ${file.name} 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    // TODO: 调用恢复 API
    await restoreFile(file.id)
    ElMessage.success('恢复成功')
    loadTrashList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('恢复失败')
    }
  }
}

// 处理彻底删除
const handlePermanentDelete = async (file) => {
  try {
    await ElMessageBox.confirm(
      `确定要彻底删除 ${file.name} 吗？此操作不可恢复！`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    // TODO: 调用彻底删除 API
    await permanentlyDeleteFile(file.id,file.name)
    ElMessage.success('删除成功')
    loadTrashList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}


// 处理文件选择
const handleSelectionChange = (selection) => {
  selectedFiles.value = selection
}

// 处理文件点击
const handleFileClick = (file) => {
  // 在回收站中禁用文件夹导航
  if (activeNav.value === 'trash') {
    return
  }

  if (file.isFolder) {
    //currentPath.value = currentPath.value + file.name + '/'
    if (!file.path.endsWith('/')) {
      currentPath.value = file.path + '/'
    } else {
      currentPath.value = file.path
    }
    console.log('Navigating to:', currentPath.value)
    loadFileList()
  } else {
    selectedFile.value = file
    previewDialogVisible.value = true
  }
}

// 显示上传对话框
const showUploadDialog = () => {
  uploadDialogVisible.value = true
}

// 显示新建文件夹对话框
const showNewFolderDialog = () => {
  newFolderDialogVisible.value = true
}

// 处理上传成功
const handleUploadSuccess = () => {
  console.log('handleUploadSuccess')
  loadFileList()
  //ElMessage.success('��传成功')
}

// 处理文件夹创建成功
const handleFolderCreated = () => {
  loadFileList()
  ElMessage.success('文件夹创建成功')
}

// 处理分享
const handleShare = (file) => {
  selectedFile.value = file
  shareDialogVisible.value = true
}

// 处理分享成功
const handleShareSuccess = (shareLink) => {
  ElMessage.success(`分享链接已复制：${shareLink}`)
}

// 处理下载
const handleDownload = async (file) => {
  try {
    const response = await downloadFile(file.id)
    
    // 创建 Blob URL 并触发下载
    const blob = new Blob([response.data])
    const downloadUrl = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = downloadUrl
    link.download = file.name
    document.body.appendChild(link)
    link.click()
    
    // 清理
    window.URL.revokeObjectURL(downloadUrl)
    document.body.removeChild(link)
    
    ElMessage.success('下载成功')
  } catch (error) {
    console.error('Download error:', error)
    ElMessage.error('下载失败：' + error.message)
  }
}

// 处理删除
const handleDelete = async (file) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除 ${file.name} 吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteFile(file.id,file.name)
    ElMessage.success('删除成功')
    loadFileList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 处理退出登录
const handleLogout = () => {
  localStorage.removeItem('token')
  localStorage.removeItem('username')
  router.push('/login')
}

onMounted(() => {
  if (activeNav.value === 'trash') {
    loadTrashList()
  } else {
    loadFileList(activeNav.value)
  }
})
</script>